package config

import (
	"bufio"
	"io"
	"os"
	"strconv"
	"strings"
	log "ac-common-go/glog"
)

const middle = "========="

var ConfigInfo *Config

type Config struct {
	Mymap  map[string]string
	strcet string
}

func (c *Config) InitConfig(path string) {
	c.Mymap = make(map[string]string)

	f, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		s := strings.TrimSpace(string(b))
		if strings.Index(s, "#") == 0 {
			continue
		}

		n1 := strings.Index(s, "[")
		n2 := strings.LastIndex(s, "]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			c.strcet = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		if len(c.strcet) == 0 {
			continue
		}
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}

		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second, "\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, "\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}

		key := c.strcet + middle + frist
		c.Mymap[key] = strings.TrimSpace(second)
	}
}

func GetConfigValue(node, key string) string {
	defer func() {
		if err := recover(); err != nil {
			log.Errorf("get config value error: %s+%s, %+v", node, key, err)
		}
	}()
	mapKey := node + middle + key
	//	log.Infof("mapkey:%s", mapKey)
	v, found := ConfigInfo.Mymap[mapKey]
	if !found {
		return ""
	}

	return v
}

func GetConfigIntValue(node, key string) (int, bool) {
	strVal := GetConfigValue(node, key)
	if strVal != "" {
		intVal, err := strconv.Atoi(strVal)
		return intVal, err == nil
	} else {
		return 0, false
	}
}
func InitConfigInfo(path string) {
	myConfig := new(Config)
	myConfig.InitConfig(path)
	ConfigInfo = myConfig
}
